package Hxw3DEngine.asset.parsers
{
	import Hxw3DEngine.asset.parsers.texture.ATFDataVO;
	import flash.utils.Endian;
	import flash.display3D.Context3DTextureFormat;
	/**
	 * ...
	 * @author lighter
	 */
	public class ATFParser extends ParserBase
	{
		private var _url:String;
		private var _atf:ATFDataVO;
		private var length:uint;
		
		public function ATFParser(url:String)
		{
			_url = url;
			_atf = new ATFDataVO();
		}
		
		override public function proceedParsing():Boolean
		{
			if (!startedParsing)
			{
				startedParsing = true;
			}
			if (hasTime())
			{
				targetData.endian = Endian.LITTLE_ENDIAN;
				targetData.position = 0;
				
				var sign:String = targetData.readUTFBytes(3);
				if (sign != "ATF")
				{
					error = new Error("ATF parsing error, unknown format " + sign);
					return true;
				}
				
				if (targetData[6] == 255)
				{
					targetData.position = 7; // new file version	ATF + 0x000000FF.
					var version:uint = targetData.readUnsignedByte();
					
					length = (targetData.readUnsignedByte()<<24) +
								(targetData.readUnsignedByte()<<16) + 
								(targetData.readUnsignedByte()<<8) + 
								targetData.readUnsignedByte();
				}
				else
				{
					length = (targetData.readUnsignedByte() << 16) + (targetData.readUnsignedByte() << 8) + targetData.readUnsignedByte();
				}
				
				var tdata:uint = targetData.readUnsignedByte();
				_atf.type = tdata >> 7; 		// UB[1]
				var format:uint = tdata & 0x7f;	// UB[7]
				switch (format) {
					case 0:
					case 1:
						_atf.format = Context3DTextureFormat.BGRA;
						break;
					case 2:
					case 3:
						_atf.format = Context3DTextureFormat.COMPRESSED;
						break;
					case 4:
					case 5:
						_atf.format = "compressedAlpha";
						break; // explicit string to stay compatible 
					// with older versions
					default:
						error =  new Error("Invalid ATF format");
						return true;
				}
			
			
				_atf.width = Math.pow(2, targetData.readUnsignedByte());
				_atf.height = Math.pow(2, targetData.readUnsignedByte());
				_atf.numTextures = targetData.readUnsignedByte();
				
				targetData.position = 0;
				_atf.ba = targetData;
				return true;
			}
			return false;
		}
		
		public function get atf():ATFDataVO 
		{
			return _atf;
		}
		
		public function get url():String 
		{
			return _url;
		}
	}

}